#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./itk-4.13.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then
    echo "请输入正确的构建路径"
    exit 1
fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then
    echo "请输入正确的安装路径"
    exit 1
fi

get_itk()
{
cnt=1
number=10
while [ $cnt -lt $number ]
do
    set +e
    echo "正在下载itk，时间较长，请耐心等待......"
    wget -c -P $buildpath https://github.com/InsightSoftwareConsortium/ITK/releases/download/v4.13.3/InsightToolkit-4.13.3.tar.gz
    result_code=$?
    if [ $result_code -ne 0 ];then
        cnt=$[$cnt+1]
    else
        echo "下载itk成功"
        break
    fi
done

if [ $cnt -eq $number ];then
    echo "下载itk失败，请重新执行脚本"
    exit
fi
set -e 
}

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar cmake environment-modules 
get_itk
tar -zxvf $buildpath/InsightToolkit-4.13.3.tar.gz -C $buildpath && rm -rf $buildpath/InsightToolkit-4.13.3.tar.gz
mkdir $buildpath/itk_bin
cd $buildpath/itk_bin
cmake ../InsightToolkit-4.13.3 -DCMAKE_INSTALL_PREFIX=$installpath/ITK -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_Fortran_COMPILER=flang -DModule_AnisotropicDiffusionLBR:BOOL=ON 
for file in $(find . -name flags.make); do sed -i 's/-O2/-O1/g' $file; done
for file in $(find . -name link.txt); do sed -i 's/-O2/-O1/g' $file; done
make -j$(nproc)
make -j$(nproc) install

cat >"$installpath/ITK/itk_modulefiles" <<EOF
#%Module1.0
conflict itk
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
        set modfile_path [file dirname \$modfile]
            return \$modfile_path
    }
set pwd [getModulefileDir]
set ITK \$pwd
setenv ITK \$ITK
prepend-path ITK_DIR \$ITK
EOF
rm -rf $buildpath/InsightToolkit-4.13.3
rm -rf $buildpath/itk_bin
